<template>
	<view class="bind-container" :key="componentKey">
		<view class="desc">请选择连接设备的方式</view>

		<!-- 统一连接按钮 -->
		<button class="bind-button" @click="onConnect">
			连接设备
		</button>

		<!-- 相机组件: 保留用于扫描二维码 -->
		<view v-show="isShow" class="container">
			<camera id="camera" device-position="back" flash="off"></camera>
		</view>

		<!-- 蓝牙设备列表弹框 -->
		<view v-if="showBLEDevicesPopup" class="ble-popup-mask">
			<view class="ble-popup">
				<view class="popup-title">附近蓝牙设备</view>
				<scroll-view class="ble-device-list" scroll-y>
					<view class="ble-device-item" v-for="(dev, index) in bleDevices" :key="dev.deviceId"
						@click="onSelectBLEDevice(dev)">
						<view class="device-name">{{ dev.name || '未知设备' }}</view>
						<view class="device-id">{{ dev.deviceId }}</view>
						<view v-if="connectingDeviceId === dev.deviceId" class="connecting-tip">
							{{ connectStatus }}
						</view>
					</view>
				</scroll-view>
				<view class="popup-actions">
					<button @click="onCancelBLEList">关闭</button>
				</view>
			</view>
		</view>

		<!-- 输入WIFI信息弹框 -->
		<view v-if="showWiFiPopup" class="name-edit-popup">
			<view class="name-edit-popup-content">
				<view class="popup-title">配置设备Wi-Fi</view>
				<text>请输入正确的WIFI信息：</text>
				<input class="name-input" v-model="wifiSSID" placeholder="请输入Wi-Fi名称(SSID)" />
				<input class="name-input" v-model="wifiPassword" placeholder="请输入Wi-Fi密码" />
				<view class="popup-actions">
					<button @click="onCancelWiFiConfig">取消</button>
					<button @click="onConfirmWiFiConfig">确定</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		addClock
	} from '@/src/api/clock.js'
	import {
		SERVICE_ID,
		CHARACTERISTIC_ID
	} from '@/src/config.js'

	export default {
		data() {
			return {
				openid: getApp().globalData.openid || uni.getStorageSync("openid"),
				isShow: false,
				componentKey: 1,
				connectStatus: '',
				connectingDeviceId: '',

				// BLE设备
				showBLEDevicesPopup: false,
				bleDevices: [],
				deviceSearchTimeout: null,

				// Wi-Fi配置
				showWiFiPopup: false,
				wifiSSID: '',
				wifiPassword: '',

				// 蓝牙信息
				deviceId: '',
				serviceId: `${SERVICE_ID}`,
				characteristicId: `${CHARACTERISTIC_ID}`
			}
		},
		methods: {
			/* ========== 统一连接流程 ========== */
			async onConnect() {
				try {
					// 请求相机权限
					const cameraAuth = await this.requestCameraPermission()
					if (!cameraAuth) {
						uni.showToast({
							title: '相机权限被拒绝',
							icon: 'none'
						})
						return
					}

					// 扫描二维码获取 deviceId
					const scannedDeviceId = await this.scanQRCode()
					if (!scannedDeviceId) {
						uni.showToast({
							title: '未获取到设备ID',
							icon: 'none'
						})
						return
					}

					// 显示系统加载中
					uni.showLoading({
						title: '加载中...',
						mask: true
					})

					// 请求蓝牙权限并初始化蓝牙适配器
					const bluetoothAuth = await this.requestBluetoothPermission()
					if (!bluetoothAuth) {
						uni.showToast({
							title: '蓝牙权限被拒绝',
							icon: 'none'
						})
						uni.hideLoading()
						return
					}

					// 开始搜索蓝牙设备
					await this.startBLEDiscovery()

					// 等待设备被发现并匹配
					const device = await this.findBLEDevice(scannedDeviceId)
					if (!device) {
						uni.showToast({
							title: '未找到匹配的蓝牙设备',
							icon: 'none'
						})
						uni.hideLoading()
						this.onCancelBLEList() // 清理操作
						return
					}

					// 连接到匹配的蓝牙设备
					await this.connectToDevice(device.deviceId)

					// 隐藏加载中
					uni.hideLoading()

					// 显示 Wi-Fi 配置弹框
					this.showWiFiPopup = true

				} catch (error) {
					console.error('连接流程出错:', error)
					uni.showToast({
						title: error.message || '连接失败',
						icon: 'none'
					})
					uni.hideLoading()
				}
			},

			// 扫描二维码
			scanQRCode() {
				return new Promise((resolve, reject) => {
					uni.scanCode({
						onlyFromCamera: true,
						success: (res) => {
							console.log('扫码结果:', res)
							// const deviceId = res.result // 根据实际情况解析
							const deviceId = '24:EC:4A:02:A0:0E'
							resolve(deviceId)
						},
						fail: (err) => {
							console.error('扫描失败:', err)
							resolve(null)
						}
					})
				})
			},

			// 请求相机权限
			requestCameraPermission() {
				return new Promise((resolve, reject) => {
					uni.authorize({
						scope: 'scope.camera',
						success: () => resolve(true),
						fail: () => resolve(false)
					})
				})
			},

			// 请求蓝牙权限并初始化蓝牙适配器
			requestBluetoothPermission() {
				return new Promise((resolve, reject) => {
					uni.openBluetoothAdapter({
						success: () => {
							console.log('蓝牙适配器初始化成功')
							resolve(true)
						},
						fail: (err) => {
							console.error('openBluetoothAdapter失败:', err)
							resolve(false)
						}
					})
				})
			},

			// 开始搜索附近蓝牙设备
			startBLEDiscovery() {
				return new Promise((resolve, reject) => {
					this.bleDevices = []
					uni.startBluetoothDevicesDiscovery({
						allowDuplicatesKey: false,
						success: (res) => {
							console.log('开始搜索蓝牙设备...', res)
							uni.onBluetoothDeviceFound(this.onBLEDeviceFound.bind(this))

							// 设置搜索超时（例如5秒）
							this.deviceSearchTimeout = setTimeout(() => {
								if (this.bleDevices.length === 0) {
									uni.showModal({
										title: '提示',
										content: '未搜索到设备，请确认已打开蓝牙和定位',
										showCancel: false
									})
								}
								resolve()
							}, 5000)
						},
						fail: (err) => {
							console.error('搜索蓝牙设备失败', err)
							reject(new Error('搜索蓝牙设备失败'))
						}
					})
				})
			},

			// 处理发现的蓝牙设备
			onBLEDeviceFound(deviceRes) {
				let devs = deviceRes.devices || []
				devs.forEach(d => {
					if (!d.deviceId) return
					if (!this.bleDevices.find(x => x.deviceId === d.deviceId)) {
						d.name = d.name || d.localName || '未知设备'
						this.bleDevices.push(d)
					}
				})
			},

			// 查找匹配的蓝牙设备
			findBLEDevice(scannedDeviceId) {
				return new Promise((resolve, reject) => {
					const checkDevice = () => {
						const device = this.bleDevices.find(d => d.deviceId === scannedDeviceId)
						if (device) {
							resolve(device)
						} else {
							resolve(null)
						}
					}

					// 立即检查
					checkDevice()

					// 5秒后再次检查
					setTimeout(() => {
						checkDevice()
					}, 5000)
				})
			},

			// 连接到指定的蓝牙设备
			connectToDevice(deviceId) {
				return new Promise((resolve, reject) => {
					uni.createBLEConnection({
						deviceId: deviceId,
						success: (connRes) => {
							console.log('蓝牙连接成功 =>', connRes)
							this.deviceId = deviceId
							// 设置蓝牙最大传输单元  需在 uni.createBLEConnection调用成功后调用，mtu 设置范围 (22,512)。安卓5.1以上有效。
							uni.setBLEMTU({
								deviceId: this.deviceId,
								mtu: 512
							});
							resolve(true)
						},
						fail: (err) => {
							console.error('蓝牙连接失败', err)
							reject(new Error('蓝牙连接失败'))
						}
					})
				})
			},

			// 取消蓝牙设备列表弹框
			onCancelBLEList() {
				this.showBLEDevicesPopup = false
				uni.stopBluetoothDevicesDiscovery()
				uni.offBluetoothDeviceFound(this.onBLEDeviceFound)
				if (this.deviceSearchTimeout) {
					clearTimeout(this.deviceSearchTimeout)
				}
				uni.closeBluetoothAdapter({
					success(res) {
						console.log("关闭蓝牙适配器：", res)
					}
				})
			},

			/* ========== Wi-Fi 配置相关方法 ========== */

			// 取消Wi-Fi配置
			onCancelWiFiConfig() {
				this.showWiFiPopup = false
				this.disconnectBluetooth()
			},

			// 确认Wi-Fi配置
			async onConfirmWiFiConfig() {
				try {
					const {
						wifiSSID,
						wifiPassword,
						deviceId,
						serviceId,
						characteristicId
					} = this

					if (!wifiSSID || !wifiPassword) {
						uni.showToast({
							title: '请填写完整的Wi-Fi信息',
							icon: 'none'
						})
						return
					}

					const sendStr = `ssid=${wifiSSID};pwd=${wifiPassword}`
					const buffer = this.stringToArrayBuffer(sendStr)

					console.log('设备信息 =>', deviceId, serviceId, characteristicId, buffer)
					await this.writeBLECharacteristicValue(deviceId, serviceId, characteristicId, buffer)

					// 绑定设备到后端
					await this.bindDevice(deviceId, `闹钟${deviceId}`, 1)

					this.onBindSuccess(this.alarmName)

				} catch (error) {
					console.error('配置Wi-Fi失败:', error)
					uni.showToast({
						title: error.message || '配置Wi-Fi失败',
						icon: 'none'
					})
				} finally {
					this.showWiFiPopup = false
					this.wifiSSID = ''
					this.wifiPassword = ''
					this.disconnectBluetooth()
				}
			},

			// 写入蓝牙特征值
			writeBLECharacteristicValue(deviceId, serviceId, characteristicId, buffer) {
				return new Promise((resolve, reject) => {
					uni.writeBLECharacteristicValue({
						deviceId: deviceId,
						serviceId: serviceId,
						characteristicId: characteristicId,
						value: buffer,
						writeType: 'writeNoResponse',
						success: (res) => {
							console.log('写入 WiFi 成功 =>', res)
							resolve(res)
						},
						fail: (err) => {
							console.error('写入WiFi失败 =>', err)
							reject(new Error('写入WiFi失败'))
						}
					})
				})
			},

			// 断开蓝牙连接
			disconnectBluetooth() {
				if (this.deviceId) {
					uni.closeBLEConnection({
						deviceId: this.deviceId,
						success: (res) => {
							console.log("断开蓝牙连接：", res)
							this.deviceId = ''
						},
						fail: (err) => {
							console.error("断开蓝牙连接失败：", err)
						}
					})
				}
			},

			// 把字符串转 ArrayBuffer
			stringToArrayBuffer(str) {
				let buffer = new ArrayBuffer(str.length)
				let dataView = new DataView(buffer)
				for (let i = 0; i < str.length; i++) {
					dataView.setUint8(i, str.charCodeAt(i))
				}
				return buffer
			},

			// 绑定设备到后端
			async bindDevice(deviceId, alarmName, bindSource) {
				let paramObj = {
					openId: this.openid,
					deviceId,
					clockName: alarmName,
					bindSource
				}
				const res = await addClock(paramObj)
				console.log('bindDevice =>', res)
				if (res.status == 200) {
					uni.showToast({
						title: '绑定成功',
						icon: 'success',
						duration: 3000
					})
				} else {
					uni.showToast({
						title: res.message || '绑定失败',
						icon: 'none'
					})
					throw new Error(res.message)
				}
			},

			// 绑定成功后的处理
			onBindSuccess(alarmName) {
				uni.navigateBack({
					delta: 1
				})
			}
		},
		beforeDestroy() {
			// 清理所有蓝牙监听
			uni.offBluetoothDeviceFound(this.onBLEDeviceFound)
			uni.offBLEConnectionStateChange()
		}
	}
</script>

<style>
	.bind-container {
		padding: 20px;
	}

	.desc {
		font-size: 14px;
		color: #666;
		margin-bottom: 20px;
	}

	.bind-button {
		display: block;
		background-color: #07c160;
		color: #fff;
		padding: 10px 20px;
		margin-bottom: 10px;
		border-radius: 4px;
		text-align: center;
		font-size: 16px;
	}

	/* 弹框公共样式 */
	.name-edit-popup {
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.4);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 9999;
	}

	.name-edit-popup-content {
		background: #fff;
		width: 80%;
		max-width: 400px;
		padding: 20px;
		border-radius: 6px;
		box-sizing: border-box;
	}

	.name-input {
		width: 100%;
		height: 40px;
		padding: 5px 10px;
		border: 1px solid #ccc;
		box-sizing: border-box;
		margin-bottom: 15px;
	}

	.popup-title {
		font-size: 16px;
		font-weight: bold;
		margin-bottom: 15px;
	}

	.popup-actions {
		display: flex;
		justify-content: flex-end;
		gap: 15px;
	}

	/* BLE 设备弹框 - 遮罩 */
	.ble-popup-mask {
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.6);
		z-index: 9999;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	/* BLE 弹框主体 */
	.ble-popup {
		background: #fff;
		width: 80%;
		max-width: 450px;
		height: 66vh;
		display: flex;
		flex-direction: column;
		border-radius: 6px;
		padding: 15px;
		box-sizing: border-box;
	}

	.popup-title {
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 10px;
	}

	.ble-device-list {
		flex: 1;
		margin-top: 10px;
		background-color: #f9f9f9;
		border-radius: 4px;
		padding: 5px;
		overflow-y: auto;
		box-sizing: border-box;
	}

	.ble-device-item {
		background: #fff;
		border: 1px solid #eee;
		border-radius: 4px;
		margin-bottom: 8px;
		padding: 10px;
	}

	.device-name {
		font-weight: bold;
		color: #333;
	}

	.device-id {
		font-size: 12px;
		color: #999;
	}

	.connecting-tip {
		margin-top: 5px;
		font-size: 12px;
		color: #409eff;
	}
</style>